package com.link4a.doms.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.link4a.doms.model.Module;
import com.link4a.doms.model.User;

/**
 * @author brown
 */
@Component
public final class SessionContext {
	
	@Autowired(required=false)
	private HttpServletRequest request;

	public static final String SESSION_KEY_LOGIN_USER = "_userinfo";

	public void onUserLogin(User user, List<Module> menus, List<String> permissions) {
		request.getSession().setAttribute(SESSION_KEY_LOGIN_USER, new UserWrapper(user, menus, permissions));
	}
	
	public void onUserLogout() {
		request.getSession().setAttribute(SESSION_KEY_LOGIN_USER, null);
		request.getSession().invalidate();
	}

	public UserWrapper getUserWrapper() {
		Object wrapper = request.getSession().getAttribute(SESSION_KEY_LOGIN_USER);
		return wrapper == null ? null : (UserWrapper)wrapper;
	}

	public User getUser() {
		UserWrapper userWrapper = getUserWrapper();
		return userWrapper == null ? null : userWrapper.getUser();
	}
	
	public void put(String key, Object val) {
		request.getSession().setAttribute(key, val);
	}
	
	public Object get(String key) {
		return request.getSession().getAttribute(key);
	}

	public boolean isSessionAlive() {
		return getUser() != null;
	}
}
